package main

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strconv"
	"time"

	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/lib/pq"
	_ "github.com/mattn/go-sqlite3"
	_ "github.com/sijms/go-ora/v2"
)

var datadbMap map[string]orm.Ormer
var default_i int = 0
var imageMap map[string]interface{}
var MapJson map[string]interface{}

// TestData 函数用于测试数据连接
func (a *App) TestData(data map[string]interface{}) map[string]interface{} {
	dataMap, _ := linkData(data)
	return dataMap
}

// SaveData 函数用于保存数据到数据库
func (a *App) SaveData(data map[string]interface{}) map[string]interface{} {
	if MapJson == nil {
		MapJson = make(map[string]interface{})
	}
	timestamp := time.Now().Unix()
	id := strconv.FormatInt(timestamp, 10)
	data["id"] = id
	fmt.Println("data:", data)
	if MapJson["dataList"] == nil {
		MapJson["dataList"] = make(map[string]interface{})
	}
	MapJson["dataList"].(map[string]interface{})[id] = data
	dataMap := SaveConfig()
	dataMap["code"] = 200
	dataMap["msg"] = "保存成功"
	return dataMap
}

// GetConfig 函数用于获取配置文件
func (a *App) GetConfig() []interface{} {
	MapJson = make(map[string]interface{})
	wd, _ := os.Getwd()
	filePath := wd + "\\dataList.json" // 替换为你想要检查的文件的路径
	_, err := os.Stat(filePath)
	if err == nil {
		file, _ := os.Open(filePath)
		content, _ := io.ReadAll(file)
		if err = json.Unmarshal(content, &MapJson); err != nil {
			fmt.Printf("JSON解析失败: %v", err)
		}
	} else if os.IsNotExist(err) {
		os.Create(filePath)
		fmt.Printf("文件 %s 不存在\n", filePath)
	} else {
		fmt.Printf("检查文件 %s 时发生错误: %v\n", filePath, err)
	}
	dataList := make([]interface{}, 0)
	if MapJson["dataList"] == nil {
		MapJson["dataList"] = make(map[string]interface{})
	} else {
		for _, value := range MapJson["dataList"].(map[string]interface{}) {
			dataList = append(dataList, value)
		}
	}
	return dataList
}

func (a *App) DeleteConfig(indexList []string) map[string]interface{} {
	for _, index := range indexList {
		delete(MapJson["dataList"].(map[string]interface{}), index)
	}
	fmt.Println("MapJson:", MapJson)
	dataMap := SaveConfig()
	dataMap["code"] = 200
	dataMap["msg"] = "删除成功"
	return dataMap
}

func (a *App) Metadata(id string) map[string]interface{} {
	data := MapJson["dataList"].(map[string]interface{})[id].(map[string]interface{})
	dataType := data["dataType"].(string)
	dataMap := make(map[string]interface{})
	dataMap["code"] = 200
	if dataType == "mysql" {
		List, err := InitMysql(data)
		if err != nil {
			dataMap["code"] = 500
			dataMap["msg"] = err.Error()
		}
		dataMap["data"] = List
	} else if dataType == "postgres" {
		List, err := InitPostgres(data)
		if err != nil {
			dataMap["code"] = 500
			dataMap["msg"] = err.Error()
		}
		dataMap["data"] = List
	} else if dataType == "oracle" {
		List, err := InitOracle(data)
		if err != nil {
			dataMap["code"] = 500
			dataMap["msg"] = err.Error()
		}
		dataMap["data"] = List
	}
	return dataMap
}
